package com.example.sneakerappforme1105;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sneakerappforme1105.adapter.AddressAdapter;
import com.example.sneakerappforme1105.bean.Address;
import com.example.sneakerappforme1105.bean.CartItem;
import com.example.sneakerappforme1105.bean.Goods;
import com.example.sneakerappforme1105.dao.AddressDao;
import com.example.sneakerappforme1105.util.ToastUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.map.geolocation.TencentPoi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.function.LongFunction;

public class AddressActivity extends AppCompatActivity{
    // 管理地址的
    private String TAG = "AddressActivity";
    private Long mUserId;
    private Long mCartId;
    private ImageView iv_back2;  // 返回
    private TextView tv_title2;
    private TextView tv_add;    // 新增地址
    private RecyclerView rv_address;
    // 适配器
    private AddressAdapter adapter;
    private AlertDialog addressDialg = null; // 用来弹出窗口码数
    private AlertDialog.Builder builder = null;
    private View view_address;  // 新增地址按钮
    private AddressDao addressDao;
    private List<Address> mAddressList = new ArrayList<>(); // 初始化
    private Button bt_loc;
    private TextView tv_location_info;
    //定位管理
    private TencentLocationManager mLocationManager;
    //定位请求
    private TencentLocationRequest locationRequest;
    //权限
    private RxPermissions rxPermissions;

    private Boolean change;

    private  HashMap<Long,Goods> mGoodsMap = new HashMap<>();
    private List<CartItem> mCartItemList = new ArrayList<>();
    private Double total;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);

        mUserId = getIntent().getLongExtra("userId",0L);
        mCartId = getIntent().getLongExtra("cartId", 0L);
        change = getIntent().getBooleanExtra("change",false);   // 是否为切换地址
        total = getIntent().getDoubleExtra("total",0);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mGoodsMap = (HashMap<Long, Goods>) bundle.getSerializable("goodsMap");
            mCartItemList = (List<CartItem>) bundle.getSerializable("cartItemList");
//            Log.d(TAG, "接收到 mGoodsMap 大小：" + mGoodsMap.size());
//            Log.d(TAG, "接收到 mCartItemList 大小：" + mCartItemList.size());
//            cartViewModel = MainApplication.getInstance().getCartViewModel();
//            cartViewModel.setGoodsMap(mGoodsMap);
//            cartViewModel.setCartItemList(mCartItemList);
        }


        Log.d(TAG,"活动启动");
        Log.d(TAG,"用户id为"+mUserId);
        addressDao = MainApplication.getInstance().getAppDatabase().addressDao();
        addressDao.deleteAddress(1L,null);
        addressDao.deleteAddress(2L,null);
        iv_back2 = findViewById(R.id.iv_back2);
        tv_title2 = findViewById(R.id.tv_title2);
        tv_add = findViewById(R.id.tv_add); // 点击 跳出弹窗

        mAddressList = addressDao.getAllAddressesByUserId(mUserId);
        Log.d(TAG,"当前用户地址数据为"+mAddressList.size());
        rv_address = findViewById(R.id.rv_address); // 展示地址 长按删除
        LinearLayoutManager llm = new LinearLayoutManager(AddressActivity.this);
        rv_address.setLayoutManager(llm);
        adapter = new AddressAdapter(mAddressList,this);
        rv_address.setAdapter(adapter);

        iv_back2.setOnClickListener(view -> finish());   // 返回
        tv_title2.setText("收货地址");
        view_address = LayoutInflater.from(this).inflate(R.layout.dialogue_address, null, false);
        builder = new AlertDialog.Builder(this);
        builder.setView(view_address);
        addressDialg = builder.create();
        //实例化
        rxPermissions = new RxPermissions(this);
        tv_location_info = findViewById(R.id.tv_location_info);

        adapter.setUpdateListener(new AddressAdapter.updateAddressListener() {
            @Override
            public void updateAddress(View v, int position) {
                Address item = mAddressList.get(position);
                addressDialg.show();
                if(view_address!=null){
                    EditText et_detailAddress =view_address.findViewById(R.id.et_detailAddress);
                    EditText et_shouhuo = view_address.findViewById(R.id.et_shouhuo);
                    EditText et_tel = view_address.findViewById(R.id.et_tel);

                    et_detailAddress.setText(item.getDetailedAddress());
                    et_shouhuo.setText(item.getUsername());
                    et_tel.setText(item.getPhoneNumber());

                    view_address.findViewById(R.id.bt_back).setOnClickListener(view -> {
                        addressDialg.dismiss();
                    });

                    view_address.findViewById(R.id.bt_saveAddress).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if(view_address!=null){

                                // 保存地址
                                // 插入还是更新
                                String detailAddress = et_detailAddress.getText().toString();
                                String shouhuo = et_shouhuo.getText().toString();
                                String tel = et_tel.getText().toString();

                                if(detailAddress!=null){
                                    if(shouhuo!=null){
                                        if(tel!=null){
                                            item.setDetailedAddress(detailAddress);
                                            item.setUsername(shouhuo);
                                            item.setPhoneNumber(tel);
                                            addressDao.updateAddress(item);
                                            mAddressList.set(position,item);
                                            adapter.notifyDataSetChanged();
                                            ToastUtil.show(AddressActivity.this,"保存地址成功");
                                            addressDialg.dismiss();// 关闭

                                        }else{
                                            ToastUtil.show(AddressActivity.this,"收货电话不能为空");
                                        }
                                    }else {
                                        ToastUtil.show(AddressActivity.this,"收货人名字不能为空");
                                    }
                                }else{
                                    ToastUtil.show(AddressActivity.this,"详细地址不能为空");
                                }

                            }
                        }
                    }); // view_address




//                    view_address.findViewById(R.id.bt_location).setOnClickListener(view -> {
////                        mLocationManager.requestSingleFreshLocation(null,AddressActivity.this, Looper.getMainLooper());
//                        mLocationManager.requestSingleFreshLocation(locationRequest,AddressActivity.this, Looper.getMainLooper());
//                    });

                }


            }
        });

        adapter.setButtonListener(new AddressAdapter.OnButtonListener() {
            @Override
            public void onButtonClick(View view, int position) {
                // 获取要删除的地址对象
                Address addressToDelete = mAddressList.get(position);

                // 创建 AlertDialog
                AlertDialog.Builder builder = new AlertDialog.Builder(AddressActivity.this);
                builder.setTitle("删除地址");
                builder.setMessage("您确定要删除该地址吗？");

                // 设置否定按钮
                builder.setNegativeButton("我再想想", (dialog, which) -> {
                    dialog.dismiss(); // 关闭对话框
                });

                // 设置确定按钮
                builder.setPositiveButton("确定", (dialog, which) -> {
                    // 删除地址逻辑
                    new Thread(() -> {
                        addressDao.deleteAddress(addressToDelete.getAddressId(), mUserId); // 调用删除方法
                        runOnUiThread(() -> {
                            mAddressList.remove(position); // 从列表中移除地址
                            adapter.notifyItemRemoved(position); // 通知 Adapter 删除了某一项
                            ToastUtil.show(AddressActivity.this, "地址已删除");
                        });
                    }).start();
                });

                // 显示对话框
                builder.create().show();
            }
        });

        adapter.setClickListener(new AddressAdapter.OnClickListener() {
            @Override
            public void click(View v, int position) {
                if(change){
                    //如果是切换地址过来的
                    Intent intent = new Intent(AddressActivity.this,PurcharseActivity.class);
                    intent.putExtra("pos",position);
                    Log.d(TAG,"pos"+position);
                    intent.putExtra("userId",mUserId);
                    intent.putExtra("cartId",mCartId);
                    intent.putExtra("total",total);
                    Bundle bundle2 = new Bundle();
                    bundle2.putSerializable("goodsMap", mGoodsMap);
                    bundle2.putSerializable("cartItemList", new ArrayList<>(mCartItemList));
                    intent.putExtras(bundle2);
                    startActivity(intent);
                }
            }
        });


        // 新增地址
        findViewById(R.id.tv_add).setOnClickListener(view -> {
            addressDialg.show();;   // 展示窗口
            if(view_address!=null){
                EditText et_detailAddress =view_address.findViewById(R.id.et_detailAddress);
                EditText et_shouhuo = view_address.findViewById(R.id.et_shouhuo);
                EditText et_tel = view_address.findViewById(R.id.et_tel);
                et_detailAddress.setText("");
                et_shouhuo.setText("");
                et_tel.setText("");

                view_address.findViewById(R.id.bt_back).setOnClickListener(view1 -> {
                    addressDialg.dismiss();
                });

                view_address.findViewById(R.id.bt_saveAddress).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(view_address!=null){

                            // 保存地址
                            // 插入还是更新
                            String detailAddress = et_detailAddress.getText().toString();
                            String shouhuo = et_shouhuo.getText().toString();
                            String tel = et_tel.getText().toString();

                            if(!detailAddress.equals("")){
                                if(!shouhuo.equals("")){
                                    if(!tel.equals("")){
                                        Address address = new Address(mUserId,shouhuo,tel,detailAddress);
                                        long newId = addressDao.insert(address);
                                        address.setAddressId(newId);
                                        ToastUtil.show(AddressActivity.this,"保存地址成功");
                                        addressDialg.dismiss();// 关闭
                                        mAddressList.add(address);
                                        adapter.notifyDataSetChanged();
                                    }else{
                                        ToastUtil.show(AddressActivity.this,"收货电话不能为空");
                                    }
                                }else {
                                    ToastUtil.show(AddressActivity.this,"收货人名字不能为空");
                                }
                            }else{
                                ToastUtil.show(AddressActivity.this,"详细地址不能为空");
                            }

                        }
                    }
                }); // view_address


            }
        });
    }





    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "活动重新启动");
        adapter.notifyDataSetChanged(); // 刷新recyle
    }









}